﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.QPZS.EPC.API.Domain;
using Wicture.QPZS.EPC.API.Domain.Entities;
using Wicture.QPZS.EPC.API.Repository;

namespace Wicture.QPZS.EPC.API.Throtteds.VinPrices
{
    public class VinPriceProviderProxy : IVinPriceProviderProxy
    {
        public const string OtherVinBrandCode = "other";
        private readonly IServiceRepository _serviceRepository;
        private readonly IApiVinPriceProvider[] _apiVinPriceProviders;

        public VinPriceProviderProxy(IServiceRepository serviceRepository, IApiVinPriceProvider[] apiVinPriceProviders)
        {
            _serviceRepository = serviceRepository;
            _apiVinPriceProviders = apiVinPriceProviders;
        }

        public decimal Provide(ThrottlingContext context)
        {
            return ProvideInternal(context);
            //var provider = SelectProvider(context);
            //if (provider == null)
            //{
            //    return ProvideInternal(context);
            //}
            //else
            //{
            //    return provider.Provide(context);
            //}
        }

        private IApiVinPriceProvider SelectProvider(ThrottlingContext context)
        {
            return _apiVinPriceProviders.FirstOrDefault(s => s.ApiName.EqualsIgnoreCase(context.ServiceDefinition.Name));
        }

        private decimal ProvideInternal(ThrottlingContext context)
        {
            decimal cost = 0;
            if (context.WithVin && !string.IsNullOrEmpty(context.BrandCode))
            {
                cost = 1;
                var brands = _serviceRepository.GetAccountPackageApiBrands(context.AccountPackageApi.Id);
                var brand = brands.FirstOrDefault(s => s.BrandCode.EqualsIgnoreCase(context.BrandCode));
                if (brand == null)
                {
                    brand = brands.FirstOrDefault(s => s.BrandCode.EqualsIgnoreCase(OtherVinBrandCode));
                }
                if ((brand?.Price ?? 0) > 0)
                {
                    cost = brand.Price;
                }
            }
            else
            {
                cost = context.AccountPackageApi.Price;
            }
            context.Cost = cost;
            return cost;
        }
    }
}
